#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.dev'

import django
django.setup()

import pymysql, datetime, requests, json, time
from django.conf import settings
from django_redis import get_redis_connection
from random import randint

from equity_mall.utils.qiniu_storage import pic_upload
from orders.models import *
from equity_mall.utils.utils import get_sign
from equity_admin.tasks import group_order_resutl_send
from equity_mall.utils.refresh_effective_cookie import push_uncluster_failure


def create_order_tb():
    table_name = f'tb_o_point_order_info_{(datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y%m%d")}'
    conn = pymysql.connect(host=settings.DATABASES['salve']['HOST'],
                           port=settings.DATABASES['salve']['PORT'],
                           database=settings.DATABASES['salve']['NAME'],
                           user=settings.DATABASES['salve']['USER'],
                           password=settings.DATABASES['salve']['PASSWORD'])
    cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)
    sql = f'''
    CREATE TABLE IF NOT EXISTS `{table_name}` (
    `id` int unsigned primary key auto_increment not null,
    `program_id` varchar(18) not null,
    `wyf_openid` varchar(32) not null,
    `unionid` varchar(32) not null,
    `shop_id` varchar(32) not null,
    `money` decimal(10, 2) not null,
    `order_type` varchar(16) not null,
    `out_trade_no` varchar(32) not null,
    `transaction_id` varchar(32) unique,
    `channel_trade_no` varchar(32) not null,
    `short_key` varchar(32) not null,
    `pay_time` datetime not null,
    `bank_type` varchar(32) not null,
    `customeruser_id` int,
    `is_point` int not null
    );
    '''
    cursor.execute(sql)
    conn.commit()
    cursor.close()
    conn.close()


def get_access_token(APP_ID, APP_SECRET):
    redis_conn = get_redis_connection("small_token")
    access_token = redis_conn.get(settings.MANAGER_APP_ID)
    if not access_token:
        small_url = f'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APP_ID}&secret={APP_SECRET}'
        small_reaponse = requests.get(small_url)
        small_data = small_reaponse.json()
        access_token = small_data['access_token']
        redis_conn.setex(APP_ID, small_data['expires_in'], access_token)
    else:
        access_token = access_token.decode()
    return access_token


def create_inviter_qrcode(inviter_id):
    APP_ID = settings.CUSTOMER_APP_ID_WYH
    APP_SECRET = settings.CUSTOMER_APP_SECRET_WYH
    access_token = get_access_token(APP_ID, APP_SECRET)
    headers = {
        "Content-Type": "application/json"
    }
    url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}'
    body = {
        "page": "pages/invite_get_integral/invite_get_integral",
        "scene": f"inviter_id={inviter_id}",
        "check_path": False,
        "env_version": "develop",
        "width": "280px"
    }
    response = requests.post(url=url, data=json.dumps(body))
    try:
        result = response.json()
        return ''
    except:
        pass
    img_str = response.content
    return pic_upload(img_str)


def cancel_group_order(group):
    check_group_order = OrderInfo.objects.filter(state=15, group_id=group.id)
    if len(check_group_order) >= group.group_order_num:
        try:
            for order in check_group_order:
                order.state=2
                order.save()
                group_order_resutl_send.delay({'openid': order.customeruservice.wyh_openid, 'order_id': order.id, 'group_state': 1})
            check_group_order.update(state=2)
        except:
            pass
        group.group_status = 2
        group.save()
        print(f'{group.id}拼团成功')
    else:
        if group.expired_time <= datetime.datetime.now():
            for order in check_group_order:
                url = 'https://api.gdwxyf.com/api/refund.do'
                datetime_now = datetime.datetime.now()
                order_id = f'{datetime_now.strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}'
                body = {
                    "program_id": "202316837141378884",
                    "shop_id": order.merchant.ruiyinxinMerchantID,
                    "refund_order_id": order_id,
                    "order_id": order.orderNum
                }
                key = '6715C7D4435343BA0459EAEC2334D81B'
                sign = get_sign(body, key)
                body['sign'] = sign
                response = requests.post(url=url, json=body)
                result = response.json()
                if result['result_code'] == 'success':
                    refund_order_data = {}
                    refund_order_data['order_id'] = order.id
                    refund_order_data['operator_role'] = 5
                    refund_order_data['refund_order_id'] = order_id
                    refund_order_data['refund_transaction_id'] = result['refund_transaction_id']
                    refund_order_data['plat_refund_order_id'] = result['plat_refund_order_id']
                    refund_order_data['refund_money'] = result['refund_money']
                    refund_order_data['refund_procedure_money'] = result['commission']
                    refund_order_data['refund_time'] = datetime.datetime.strptime(result['refund_end_time'], '%Y%m%d%H%M%S')
                    refund_order_data['remark'] = '拼团超时退款'
                    RefundOrderInfo.objects.create(**refund_order_data)
                    order.state = 8
                    order.refund_money = order.realpay_amount
                    order.out_refund_no = order_id
                    order.refund_id = result['refund_transaction_id']
                    order.save()
                    ordergoods_set = order.ordergoods_set.all()
                    for ordergoods in ordergoods_set:
                        goods = ordergoods.goods
                        launched_goods = ordergoods.launched_goods
                        count = ordergoods.count
                        origin_sales = goods.sales
                        origin_remain_stock = goods.remain_stock
                        new_sales = origin_sales - count
                        new_remain_stock = origin_remain_stock + count
                        goods.sales = new_sales
                        goods.remain_stock = new_remain_stock
                        goods.save()
                        if launched_goods:
                            launched_origin_stock = launched_goods.stock
                            launched_origin_sales = launched_goods.sales
                            launched_new_stock = launched_origin_stock + count
                            launched_new_sales = launched_origin_sales - count
                            launched_goods.stock = launched_new_stock
                            launched_goods.sales = launched_new_sales
                            launched_goods.save()
                        else:
                            origin_stock = goods.stock
                            new_stock = origin_stock + count
                            goods.stock = new_stock
                            goods.save()
                else:
                    refund_order_data = {}
                    refund_order_data['refund_status'] = 2
                    refund_order_data['operator_role'] = 5
                    refund_order_data['order_id'] = order.id
                    refund_order_data['return_msg'] = result['error_msg']
                    refund_order_data['refund_order_id'] = order_id
                    refund_order_data['refund_time'] = datetime_now
                    refund_order_data['remark'] = '拼团超时退款'
                    refund_order_data['return_msg'] = result["error_msg"]
                    RefundOrderInfo.objects.create(**refund_order_data)
                    try:
                        push_uncluster_failure(order.id)
                    except:
                        pass
                try:
                    group_order_resutl_send.delay({'openid': order.customeruservice.wyh_openid, 'order_id': order.id, 'group_state': 2})
                except:
                    pass
            group.group_status = 3
            group.save()
            print(f'{group.id}取消成功')


def check_cancel_group_order():
    '''取消超时拼团'''
    print('%s: check_cancel_group_order' % time.ctime())
    group_set = OrderInfoGROUP.objects.filter(expired_time__lte=datetime.datetime.now(), group_status=1)
    for group in group_set:
        cancel_group_order(group)


def check_cancel_order():
    '''取消超时订单'''
    today = datetime.datetime.now()
    expired_time = today + datetime.timedelta(days=-27)
    order_set = OrderInfo.objects.filter(state=2, is_profit_sharing__in=[1, 3], id__gte=7660929, payment_time__lte=expired_time).exclude(id__in=[7672020,7672045,7674242,7674956,7675471,7676300,7678324,7678942,7683071,7684871,7684958,7685029,7685069,7685501,7685745,7685834,7686162,7686394,7686427,7686602,7687650,7687715,7687732,7688095,7688100,7688115,7688177,7689635,7690181,7690252,7691071,7691250,7691322,7691521,7691640,7691750,7691902,7691980,7692197,7692322,7692408,7692446,7692523,7692575,7692788,7692893,7692905,7692913,7692928,7692935,7693053,7693232,7693243,7693589,7693754,7693853,7693873,7694060,7694073,7694101,7694630,7695664,7695806,7696083,7696621,7696714,7697092,7697095,7697551,7697859,7697958,7698614,7698646,7698655,7698909,7699082,7699163,7699172,7699564,7699605,7699853,7699887,7699912,7699931,7699964,7700006,7700031,7700047,7700052,7700062,7700075,7700172,7700459,7700584,7700588,7700670,7700721,7700820,7700845,7700976,7700989,7700999,7701002,7701007,7701433,7701589,7701871,7701875,7701887,7701958,7702171,7702268,7702329,7702384,7702446,7702786,7702792,7702819,7702946,7703371,7703612,7703659,7703813,7704351,7709209,7709282,7709476,7710162,7710597,7710673,7710887,7711166,7711406,7711602,7711681,7711682,7712417,7712929,7713026,7713100,7713154,7713233,7713305,7713343,7713450,7713542,7713607,7713661,7713753,7713849,7713969,7713997,7714051,7714177,7714268,7714340,7714390,7714416,7714426,7714454,7714516,7714674,7714934,7714980,7715259,7715316,7715426,7715476,7715609,7715633,7715707,7715874,7716206,7716309,7716397,7716453,7716545,7716631,7716702,7716739,7716773,7716856,7716875,7716937,7717131,7717347,7717543,7717645,7718059,7718326,7718410,7718451,7718664,7718842,7718929,7719030,7719432,7719773,7720213,7720468,7720651,7720748,7720963,7721067,7721402,7721656,7721789,7721976,7722710,7722724,7722986,7723051,7723185,7723279,7723338,7723685,7723731,7723879,7724128,7724277,7724335,7724850,7724905,7725367,7725817,7726083,7726342,7726589,7727145,7727186,7727748,7727997,7728792,7728877,7728961,7729005,7729079,7729139,7730110,7730426,7730606,7730904,7730908,7730916,7730957,7731299,7731841,7733005,7733011,7733169,7733264,7733383,7733487,7733891,7734067,7736407,7737667,7738858,7739080,7739784,7740238,7740418,7740427,7740433,7740473,7740568,7740684,7741374,7741425,7742885,7743504,7743924,7743932,7744208,7744586,7745027,7745078,7745146,7745187,7745226,7745646,7745758,7746549,7746919,7747277,7747706,7747799,7747907,7748140,7748740,7749269,7749301,7749370,7749434,7749707,7749854,7749929,7750622,7750758,7750931,7751148,7752094,7752318,7752335,7752475,7752595,7752871,7752889,7753073,7753301,7753332,7753865,7754008,7754323,7754511,7754592,7754665,7754818,7754821,7754822,7754824,7754825,7754826,7754827,7754834,7754843,7754849,7754858,7754865,7754868,7754871,7754896,7754911,7754913,7754915,7754925,7755425,7756009,7756145]).exclude(id__in=[7848599,7848770,7849127,7849295,7849605,7849655,7849791,7849856,7849883,7850011,7850037,7850494,7850506,7850642,7851064,7851213,7851631,7852462,7852529,7852644,7852952,7853026,7854394,7854670,7854762,7857086,7857396,7857818,7858468,7858695,7859112,7859156,7859291,7859606,7859660,7860052,7860058,7860394,7861563,7862609,7863171,7863580,7863605,7863850,7863866,7863871,7863907,7863933,7864028,7864303,7865187,7865321,7865502,7865505,7865794,7865817,7867223,7867311,7868490,7868680,7868879,7868942,7869744,7869821,7869822,7869850,7870321,7870340,7871806,7871943,7873253,7873294,7873395,7875272,7875292,7875448,7875585,7875631,7875660,7875682,7875713,7876427,7876590,7876691,7877551,7877854,7878026,7878092,7879128,7879133,7879315,7879358,7880560,7881132,7881953,7882494,7883693,7884770,7885806,7885850,7885949,7886010,7887111,7888242,7890612,7891356,7891942,7892012,7893239,7894289,7894329,7894694,7894949,7896670,7897504,7898142,7898234,7898684,7898902,7899004,7899517,7899623,7900077,7900378,7900400,7901141,7901199,7901391,7901410,7901602,7901703,7901724,7901871,7902073,7902720,7903098,7903393,7903832,7904262,7905269,7905321,7906230,7907259,7907355,7907505,7907642,7908071,7908074,7908104,7908240,7908249,7908344,7908425,7908588,7909167,7910194,7910593,7910647,7910732,7910984,7911238,7911307,7911424,7911736,7911795,7911847,7911880,7911908,7911933,7911944,7912408,7912543,7912665,7912719,7913337,7913415,7913609,7913697,7913733,7913773,7913941,7913950,7913990,7914011,7914031,7914053,7914201,7914296,7914381,7914453,7914583,7914623,7914665,7914671,7914716,7914725,7914770,7914771,7914787,7914829,7914870,7915073,7915182,7915335,7915520,7915595,7915684,7915693,7915791,7915857,7915888,7915889,7915904,7916016,7916019,7916247,7916539,7916646,7916773,7916886,7916912,7916917,7917046,7917423,7917446,7917586,7917588,7917599,7917713,7917784,7918121,7918192,7918395,7918553,7918559,7918934,7918941,7919210,7919317,7919690,7919770,7919926,7920445,7920469,7920520,7920580,7920657,7920928,7921318,7921553,7921583,7921633,7921668,7921697,7922074,7922258,7922276,7922277,7922278,7922280,7922386,7922388,7922389,7923116,7923140,7923550,7924236,7924625,7924781,7924871,7925274,7925318,7925470,7925543,7925669,7925768,7925808,7925992,7926021,7926209,7926311,7926399,7926517,7926575,7927086,7927423,7928099,7928103,7928107,7928411,7928794,7929131,7929290,7929517,7929962,7929984,7930019,7930153,7930182,7930333,7931324,7931331,7931617,7932145,7932191,7932707,7932725,7932737,7932834,7932933,7932957,7933145,7933503,7933842,7933877,7934199,7934286,7934487,7935600,7935645,7935672,7935674,7935687,7935783,7936179,7936458,7936624,7937258,7937287,7937465,7937473,7937712,7938095,7938191,7938253,7938519,7938765,7938773,7938797,7938804,7939717,7940270,7940490,7940525,7940801,7940845,7940886,7941083,7941116,7941158,7941286,7941333,7941345,7941354,7941458,7941468,7941569,7941623,7941973,7941982,7941997,7942001,7942066,7942150,7942204,7942215,7942240,7942319,7942541,7942606,7942895,7942900,7942905,7943085,7943164,7943315,7943444,7943665,7943927,7943958,7944056,7944125,7944169,7944178,7944248,7944352,7944527,7944830,7944910,7944920,7945064,7945104,7945128,7945340,7945928,7946247,7946252,7946258,7946551,7946558,7946976,7947168,7947178,7947190,7947372,7947685,7947772,7947821,7947845,7948469,7948605,7948610,7948707,7948773,7948785,7948845,7949127,7949492,7949552,7949570,7949886,7949998,7950063,7950100,7950109,7950192,7950580,7950673,7950675,7950950,7951292,7951303,7951390,7951419,7951555,7951602,7951755,7951843,7951878,7951911,7952360,7952376,7952400,7952447,7952504,7952623,7952660,7952988,7953284,7953605,7953700,7953853,7953867,7953899,7953941,7953954,7953969,7953997,7954010,7954441,7954468,7954474,7954547,7954573,7954582,7954834,7954893,7954978,7955033,7955080,7955100,7955140,7955199,7955223,7955356,7955366,7955454,7955534,7955805,7955986,7956003,7956041,7956057,7956067,7956331,7956507,7956585,7956611,7956615,7956701,7956761,7957153,7957488,7957659,7957935,7957943,7958132,7958217,7958239,7958282,7958284,7958614,7958690,7958777,7958812,7958898,7958923,7958957,7959091,7959213,7959491,7959508,7959528,7959559,7959614,7959632,7959636,7959695,7959725,7959776,7959842,7959961,7959967,7959970,7960021,7960038,7960058,7960165,7960167,7960204,7960217,7960278,7960289,7960487,7960814,7960963,7960978,7961029,7961274,7961313,7961411,7961494,7961592,7961682,7961854,7961872,7961896,7962001,7962031,7962077,7962108,7962111,7962124,7962126,7962136,7962145,7962160,7962197,7962214,7962250,7962268,7962439,7962575,7962588,7962677,7962885,7962917,7963129,7963161,7963172,7963173])
    # order_set = OrderInfo.objects.filter(state=2, is_profit_sharing=1, id__gte=7660929, payment_time__lte=expired_time, id=7977195).exclude(id__in=[7672020,7672045,7674242,7674956,7675471,7676300,7678324,7678942,7683071,7684871,7684958,7685029,7685069,7685501,7685745,7685834,7686162,7686394,7686427,7686602,7687650,7687715,7687732,7688095,7688100,7688115,7688177,7689635,7690181,7690252,7691071,7691250,7691322,7691521,7691640,7691750,7691902,7691980,7692197,7692322,7692408,7692446,7692523,7692575,7692788,7692893,7692905,7692913,7692928,7692935,7693053,7693232,7693243,7693589,7693754,7693853,7693873,7694060,7694073,7694101,7694630,7695664,7695806,7696083,7696621,7696714,7697092,7697095,7697551,7697859,7697958,7698614,7698646,7698655,7698909,7699082,7699163,7699172,7699564,7699605,7699853,7699887,7699912,7699931,7699964,7700006,7700031,7700047,7700052,7700062,7700075,7700172,7700459,7700584,7700588,7700670,7700721,7700820,7700845,7700976,7700989,7700999,7701002,7701007,7701433,7701589,7701871,7701875,7701887,7701958,7702171,7702268,7702329,7702384,7702446,7702786,7702792,7702819,7702946,7703371,7703612,7703659,7703813,7704351,7709209,7709282,7709476,7710162,7710597,7710673,7710887,7711166,7711406,7711602,7711681,7711682,7712417,7712929,7713026,7713100,7713154,7713233,7713305,7713343,7713450,7713542,7713607,7713661,7713753,7713849,7713969,7713997,7714051,7714177,7714268,7714340,7714390,7714416,7714426,7714454,7714516,7714674,7714934,7714980,7715259,7715316,7715426,7715476,7715609,7715633,7715707,7715874,7716206,7716309,7716397,7716453,7716545,7716631,7716702,7716739,7716773,7716856,7716875,7716937,7717131,7717347,7717543,7717645,7718059,7718326,7718410,7718451,7718664,7718842,7718929,7719030,7719432,7719773,7720213,7720468,7720651,7720748,7720963,7721067,7721402,7721656,7721789,7721976,7722710,7722724,7722986,7723051,7723185,7723279,7723338,7723685,7723731,7723879,7724128,7724277,7724335,7724850,7724905,7725367,7725817,7726083,7726342,7726589,7727145,7727186,7727748,7727997,7728792,7728877,7728961,7729005,7729079,7729139,7730110,7730426,7730606,7730904,7730908,7730916,7730957,7731299,7731841,7733005,7733011,7733169,7733264,7733383,7733487,7733891,7734067,7736407,7737667,7738858,7739080,7739784,7740238,7740418,7740427,7740433,7740473,7740568,7740684,7741374,7741425,7742885,7743504,7743924,7743932,7744208,7744586,7745027,7745078,7745146,7745187,7745226,7745646,7745758,7746549,7746919,7747277,7747706,7747799,7747907,7748140,7748740,7749269,7749301,7749370,7749434,7749707,7749854,7749929,7750622,7750758,7750931,7751148,7752094,7752318,7752335,7752475,7752595,7752871,7752889,7753073,7753301,7753332,7753865,7754008,7754323,7754511,7754592,7754665,7754818,7754821,7754822,7754824,7754825,7754826,7754827,7754834,7754843,7754849,7754858,7754865,7754868,7754871,7754896,7754911,7754913,7754915,7754925,7755425,7756009,7756145]).exclude(id__in=[7848599,7848770,7849127,7849295,7849605,7849655,7849791,7849856,7849883,7850011,7850037,7850494,7850506,7850642,7851064,7851213,7851631,7852462,7852529,7852644,7852952,7853026,7854394,7854670,7854762,7857086,7857396,7857818,7858468,7858695,7859112,7859156,7859291,7859606,7859660,7860052,7860058,7860394,7861563,7862609,7863171,7863580,7863605,7863850,7863866,7863871,7863907,7863933,7864028,7864303,7865187,7865321,7865502,7865505,7865794,7865817,7867223,7867311,7868490,7868680,7868879,7868942,7869744,7869821,7869822,7869850,7870321,7870340,7871806,7871943,7873253,7873294,7873395,7875272,7875292,7875448,7875585,7875631,7875660,7875682,7875713,7876427,7876590,7876691,7877551,7877854,7878026,7878092,7879128,7879133,7879315,7879358,7880560,7881132,7881953,7882494,7883693,7884770,7885806,7885850,7885949,7886010,7887111,7888242,7890612,7891356,7891942,7892012,7893239,7894289,7894329,7894694,7894949,7896670,7897504,7898142,7898234,7898684,7898902,7899004,7899517,7899623,7900077,7900378,7900400,7901141,7901199,7901391,7901410,7901602,7901703,7901724,7901871,7902073,7902720,7903098,7903393,7903832,7904262,7905269,7905321,7906230,7907259,7907355,7907505,7907642,7908071,7908074,7908104,7908240,7908249,7908344,7908425,7908588,7909167,7910194,7910593,7910647,7910732,7910984,7911238,7911307,7911424,7911736,7911795,7911847,7911880,7911908,7911933,7911944,7912408,7912543,7912665,7912719,7913337,7913415,7913609,7913697,7913733,7913773,7913941,7913950,7913990,7914011,7914031,7914053,7914201,7914296,7914381,7914453,7914583,7914623,7914665,7914671,7914716,7914725,7914770,7914771,7914787,7914829,7914870,7915073,7915182,7915335,7915520,7915595,7915684,7915693,7915791,7915857,7915888,7915889,7915904,7916016,7916019,7916247,7916539,7916646,7916773,7916886,7916912,7916917,7917046,7917423,7917446,7917586,7917588,7917599,7917713,7917784,7918121,7918192,7918395,7918553,7918559,7918934,7918941,7919210,7919317,7919690,7919770,7919926,7920445,7920469,7920520,7920580,7920657,7920928,7921318,7921553,7921583,7921633,7921668,7921697,7922074,7922258,7922276,7922277,7922278,7922280,7922386,7922388,7922389,7923116,7923140,7923550,7924236,7924625,7924781,7924871,7925274,7925318,7925470,7925543,7925669,7925768,7925808,7925992,7926021,7926209,7926311,7926399,7926517,7926575,7927086,7927423,7928099,7928103,7928107,7928411,7928794,7929131,7929290,7929517,7929962,7929984,7930019,7930153,7930182,7930333,7931324,7931331,7931617,7932145,7932191,7932707,7932725,7932737,7932834,7932933,7932957,7933145,7933503,7933842,7933877,7934199,7934286,7934487,7935600,7935645,7935672,7935674,7935687,7935783,7936179,7936458,7936624,7937258,7937287,7937465,7937473,7937712,7938095,7938191,7938253,7938519,7938765,7938773,7938797,7938804,7939717,7940270,7940490,7940525,7940801,7940845,7940886,7941083,7941116,7941158,7941286,7941333,7941345,7941354,7941458,7941468,7941569,7941623,7941973,7941982,7941997,7942001,7942066,7942150,7942204,7942215,7942240,7942319,7942541,7942606,7942895,7942900,7942905,7943085,7943164,7943315,7943444,7943665,7943927,7943958,7944056,7944125,7944169,7944178,7944248,7944352,7944527,7944830,7944910,7944920,7945064,7945104,7945128,7945340,7945928,7946247,7946252,7946258,7946551,7946558,7946976,7947168,7947178,7947190,7947372,7947685,7947772,7947821,7947845,7948469,7948605,7948610,7948707,7948773,7948785,7948845,7949127,7949492,7949552,7949570,7949886,7949998,7950063,7950100,7950109,7950192,7950580,7950673,7950675,7950950,7951292,7951303,7951390,7951419,7951555,7951602,7951755,7951843,7951878,7951911,7952360,7952376,7952400,7952447,7952504,7952623,7952660,7952988,7953284,7953605,7953700,7953853,7953867,7953899,7953941,7953954,7953969,7953997,7954010,7954441,7954468,7954474,7954547,7954573,7954582,7954834,7954893,7954978,7955033,7955080,7955100,7955140,7955199,7955223,7955356,7955366,7955454,7955534,7955805,7955986,7956003,7956041,7956057,7956067,7956331,7956507,7956585,7956611,7956615,7956701,7956761,7957153,7957488,7957659,7957935,7957943,7958132,7958217,7958239,7958282,7958284,7958614,7958690,7958777,7958812,7958898,7958923,7958957,7959091,7959213,7959491,7959508,7959528,7959559,7959614,7959632,7959636,7959695,7959725,7959776,7959842,7959961,7959967,7959970,7960021,7960038,7960058,7960165,7960167,7960204,7960217,7960278,7960289,7960487,7960814,7960963,7960978,7961029,7961274,7961313,7961411,7961494,7961592,7961682,7961854,7961872,7961896,7962001,7962031,7962077,7962108,7962111,7962124,7962126,7962136,7962145,7962160,7962197,7962214,7962250,7962268,7962439,7962575,7962588,7962677,7962885,7962917,7963129,7963161,7963172,7963173])
    for order in order_set:
        url = 'https://api.gdwxyf.com/api/refund.do'
        datetime_now = datetime.datetime.now()
        order_id = f'{datetime_now.strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}'
        body = {
            "program_id": "202316837141378884",
            "shop_id": order.merchant.ruiyinxinMerchantID,
            "refund_order_id": order_id,
            "order_id": order.orderNum
        }
        key = '6715C7D4435343BA0459EAEC2334D81B'
        sign = get_sign(body, key)
        body['sign'] = sign
        response = requests.post(url=url, json=body)
        result = response.json()
        if result['result_code'] == 'success':
            refund_order_data = {}
            refund_order_data['order_id'] = order.id
            refund_order_data['operator_role'] = 5
            refund_order_data['refund_order_id'] = order_id
            refund_order_data['refund_transaction_id'] = result['refund_transaction_id']
            refund_order_data['plat_refund_order_id'] = result['plat_refund_order_id']
            refund_order_data['refund_money'] = result['refund_money']
            refund_order_data['refund_procedure_money'] = result['commission']
            refund_order_data['refund_time'] = datetime.datetime.strptime(result['refund_end_time'], '%Y%m%d%H%M%S')
            refund_order_data['remark'] = '订单超时未核销退款'
            RefundOrderInfo.objects.create(**refund_order_data)
            order.state = 8
            order.refund_money = order.realpay_amount
            order.out_refund_no = order_id
            order.refund_id = result['refund_transaction_id']
            order.save()
            ordergoods_set = order.ordergoods_set.all()
            for ordergoods in ordergoods_set:
                goods = ordergoods.goods
                launched_goods = ordergoods.launched_goods
                count = ordergoods.count
                origin_sales = goods.sales
                origin_remain_stock = goods.remain_stock
                new_sales = origin_sales - count
                new_remain_stock = origin_remain_stock + count
                goods.sales = new_sales
                goods.remain_stock = new_remain_stock
                goods.save()
                if launched_goods:
                    launched_origin_stock = launched_goods.stock
                    launched_origin_sales = launched_goods.sales
                    launched_new_stock = launched_origin_stock + count
                    launched_new_sales = launched_origin_sales - count
                    launched_goods.stock = launched_new_stock
                    launched_goods.sales = launched_new_sales
                    launched_goods.save()
                else:
                    origin_stock = goods.stock
                    new_stock = origin_stock + count
                    goods.stock = new_stock
                    goods.save()
        else:
            refund_order_data = {}
            refund_order_data['refund_status'] = 2
            refund_order_data['operator_role'] = 5
            refund_order_data['order_id'] = order.id
            refund_order_data['return_msg'] = result['error_msg']
            refund_order_data['refund_order_id'] = order_id
            refund_order_data['refund_time'] = datetime_now
            refund_order_data['remark'] = '订单超时未核销退款'
            refund_order_data['return_msg'] = result["error_msg"]
            RefundOrderInfo.objects.create(**refund_order_data)
    print(len(order_set))
    print(expired_time)


from merchants.models import MerchantBill

def wash_order_settle():
    ''''''
    queryset = OrderInfo.objects.filter(id__in=[9035266,9036962,9040361,9044949,9046214,9080263,9080397,9081549,9082014,9082194,9082916,9084867,9114392,9150235,9152355,9171454,9183591,9185086,9187823,9189429,9189659,9191133,9193492,9194744,9202910,9207959,9209055,9213553,9222265,9251039,9251259,9251853,9252014,9252377,9253128,9253262])
    for order in queryset:
        print(order.id)
        receipts_time = (order.payment_time+datetime.timedelta(days=30)).strftime('%Y-%m-%d')
        bill = MerchantBill.objects.filter(receipts_time=receipts_time, merchant_id=order.merchant_id,bill_type=order.order_species).first()
        if not bill:
            bill_data = {}
            bill_data['merchant_id'] = order.merchant_id
            bill_data['receipts_time'] = receipts_time
            bill_data['amount'] = order.total_price
            bill_data['commission'] = order.freight
            bill_data['level_id'] = order.merchant.level_id
            bill_data['payable_amount'] = order.total_price - order.freight
            bill_data['channel_id'] = 3
            bill_data['bill_type'] = order.order_species
            bill, create = MerchantBill.objects.get_or_create(defaults=bill_data, receipts_time=receipts_time,merchant_id=order.merchant_id,bill_type=order.order_species)
        else:
            bill.amount = bill.amount + order.total_price
            bill.commission = bill.commission + order.freight
            bill.payable_amount = bill.payable_amount + order.total_price - order.freight
            bill.save()
        order.payable_settled_amount = order.total_price - order.freight
        order.bill_id = bill.id
        order.save()


from decimal import Decimal
def wahs_settle():
    queryset = MerchantBill.objects.filter(id__in=[758598,758604,758604,754692,757505,757504,756384,771164,770142,769082,766323,766361,766388,757505,758590,753568,771269,766385,764963,755534,754692,762015,758594,758585,755540,755535,755578,755534,755536,756382,756370,756399,776528,756384,756383,756379,757502,757556,776529,757511,757543,757551,757558,757500,757510,757501,757507,776530,757505,757508,757504,776531,758585,758587,758609,758601,758590,758603,758624,758593,758608,758598,758611,758626,758597,776532,758635,758677,758658,776533,776534,776535,758663,758651,776536,758654,758656,776538,776539,758673,776540,776541,758675,776542,776543,776544,776545,776546,776547,776548,758661,776549,776550,758668,758659,776551,776552])
    for bill in queryset:
        order_set = OrderInfo.objects.filter(bill_id=bill.id)
        commission = Decimal('0')
        amount = Decimal('0')
        for order in order_set:
            amount += order.payable_amount
            commission += order.freight
        bill.amount = amount
        bill.commission = commission
        bill.payable_amount = amount -commission
        bill.save()


if __name__ == '__main__':
    pass
    wash_order_settle()